<template>
  <div class="kcjxzj-summary-edit">
    <div class="page-header">
      <h1>{{ isEdit ? '编辑' : '新建' }}课程教学总结</h1>
      <div class="actions">
        <el-button @click="router.go(-1)">
          <el-icon><Back /></el-icon> 返回
        </el-button>
      </div>
    </div>
    
    <el-card class="form-card" v-loading="loading">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="140px" label-position="left">
        <!-- 基本信息区域 -->
        <SummaryBasicInfo 
          v-model="form"
          :courses="courses"
          :terms="terms"
          :teaching-missions="teachingMissions"
          :departments="departments"
          :is-readonly="isReadonly"
          :current-mission-id="currentMissionId"
          @missions-changed="onMissionsChanged"
        />

        <!-- 成绩统计信息区域 -->
        <ScoreStatistics 
          :teaching-mission-ids="form.teachingMissionIds || []"
          :course-id="form.courseId"
          :term-id="form.termId"
        />

        <!-- 课程教学总结内容 -->
        <SummaryContentTabs v-model="form" />
        
        <!-- 操作按钮 -->
        <SummaryActionButtons
          :can-save-draft="canSaveDraft"
          :saving-draft="savingDraft"
          :submitting="submitting"
          :submit-button-text="getSubmitButtonText()"
          @save-draft="onSaveDraft"
          @submit="onSubmit"
          @cancel="onCancel"
        />
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';
import { createKcjxzj, updateKcjxzj, getKcjxzjById } from '@/api/course-teaching-summary';
import { 
  courseApi,
  termApi,
  departmentApi
} from '@/api/base-data';
import { getMyTeachingMissions } from '@/api/teaching-mission';
import { Back } from '@element-plus/icons-vue';

// 导入子组件
import SummaryBasicInfo from '@/components/summary/SummaryBasicInfo.vue';
import ScoreStatistics from '@/components/summary/ScoreStatistics.vue';
import SummaryContentTabs from '@/components/summary/SummaryContentTabs.vue';
import SummaryActionButtons from '@/components/summary/SummaryActionButtons.vue';

export default {
  name: 'EditKcjxzj',
  components: {
    Back,
    SummaryBasicInfo,
    ScoreStatistics,
    SummaryContentTabs,
    SummaryActionButtons
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const userStore = useUserStore();
    const formRef = ref(null);
    const loading = ref(false);
    const submitting = ref(false);
    const savingDraft = ref(false);
    
    const isEdit = computed(() => {
      // 如果路由参数ID是 "new"，则是新建模式
      if (route.params.id === 'new') {
        return false;
      }
      // 如果有ID且不是"new"，则是编辑模式
      return !!route.params.id;
    });
    
    // 当前操作的教学任务ID
    const currentMissionId = computed(() => {
      // 从路由参数获取当前任务ID，优先使用missionId
      return route.query.missionId || route.params.missionId || null;
    });

    // 教学任务选择变化处理
    const onMissionsChanged = (missions) => {
      // 教学任务选择变化处理
    };

    // 根据基本信息字段判断是否为只读（从教学任务生成时的只读字段）
    const isReadonly = computed(() => {
      // 如果有路由参数指定为只读模式，或者已有教学任务关联
      return route.query.readonly === 'true' || (form.value.teachingMissionIds && form.value.teachingMissionIds.length > 0);
    });
    
    const form = ref({
      courseId: '',
      termId: '',
      teachingMissionIds: [],
      departmentIds: [],
      textbook: '',
      textbookType: '',
      designAndImplementation: '',
      assessment: '',
      reflectionAndImprovement: '',
      statusId: 1 // 默认为草稿状态
    });

    // 调试：监听form.teachingMissionIds变化

    // 获取基础数据
    const courses = ref([]);
    const terms = ref([]);
    const teachingMissions = ref([]);
    const departments = ref([]);

    const fetchBaseData = async () => {
      loading.value = true;
      try {
        const [coursesData, termsData, teachingMissionsData, departmentsData] = await Promise.all([
          courseApi.getAllCourses(),
          termApi.getAllTerms(),
          getMyTeachingMissions(), // 使用权限受限的API
          departmentApi.getAllDepartments()
        ]);
        
        courses.value = coursesData || [];
        terms.value = termsData || [];
        // 权限受限的API返回分页数据，需要提取content
        teachingMissions.value = (teachingMissionsData && teachingMissionsData.content) ? teachingMissionsData.content : (teachingMissionsData || []);
        departments.value = departmentsData || [];
        
      } catch (error) {
        console.error('获取基础数据失败:', error);
        ElMessage.error('获取基础数据失败');
      } finally {
        loading.value = false;
      }
    };

    // 从课程参数初始化表单
    const initFromCourseParams = () => {
      const { courseId, termId, teachingMissionIds } = route.query;
      
      if (courseId) {
        form.value.courseId = Number(courseId);
      }
      if (termId) {
        form.value.termId = Number(termId);
      }
      if (teachingMissionIds) {
        form.value.teachingMissionIds = teachingMissionIds.split(',').map(id => Number(id));
      }
      // 注意：专业和培养层次信息现在通过course关联获取，不再从URL参数设置
    };

    // 从URL参数获取教学任务ID并预填表单（保持兼容性）
    const initFromSelectedMission = async (missionId) => {
      if (!missionId) return;
      
      loading.value = true;
      try {
        // 查找对应的教学任务
        const mission = teachingMissions.value.find(m => m.id === Number(missionId));
        if (!mission) {
          return;
        }
        
        // 预填课程、学期和教学任务ID
        form.value.courseId = mission.courseId || (mission.course && mission.course.id);
        form.value.termId = mission.termId || (mission.term && mission.term.id);
        form.value.teachingMissionIds = [Number(missionId)];
        
        // 如果课程有关联的部门，预填部门ID
        if (mission.departments && mission.departments.length > 0) {
          form.value.departmentIds = mission.departments.map(dept => dept.id);
        }
        
        // 注意：专业和培养层次信息现在通过course关联获取，不再直接设置
        
      } catch (error) {
        console.error('初始化教学任务数据失败:', error);
        ElMessage.error('初始化教学任务数据失败');
      } finally {
        loading.value = false;
      }
    };

    // 加载现有总结数据
    const loadExistingSummary = async () => {
      if (!isEdit.value) return;
      
      loading.value = true;
      try {
        const summaryData = await getKcjxzjById(route.params.id);
        if (summaryData) {
          // 填充表单数据
          form.value = {
            courseId: summaryData.courseId || summaryData.course?.id || '',
            termId: summaryData.termId || summaryData.term?.id || '',
            teachingMissionIds: summaryData.teachingMissionIds || [],
            departmentIds: summaryData.departmentIds || summaryData.departments?.map(d => d.id) || [],
            textbook: summaryData.textbook || '',
            textbookType: summaryData.textbookType || '',
            designAndImplementation: summaryData.designAndImplementation || '',
            assessment: summaryData.assessment || '',
            reflectionAndImprovement: summaryData.reflectionAndImprovement || '',
            statusId: summaryData.statusId || summaryData.status?.id || 1
          };
        }
      } catch (error) {
        console.error('加载课程教学总结数据失败:', error);
        ElMessage.error('加载课程教学总结数据失败');
      } finally {
        loading.value = false;
      }
    };

    const rules = {
      courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
      termId: [{ required: true, message: '请选择学期', trigger: 'change' }],
      textbook: [{ required: true, message: '请输入使用教材', trigger: 'blur' }],
      textbookType: [{ required: true, message: '请选择教材类别', trigger: 'change' }],
      designAndImplementation: [{ required: true, message: '请输入教学设计与实施情况', trigger: 'blur' }],
      assessment: [{ required: true, message: '请输入考试考核情况', trigger: 'blur' }],
      reflectionAndImprovement: [{ required: true, message: '请输入教学反思与改进建议', trigger: 'blur' }]
    };

    // 计算属性：是否可以暂存
    const canSaveDraft = computed(() => {
      // 只有草稿状态(1)或驳回状态(4,5,6)可以暂存
      return !form.value.statusId || [1, 4, 5, 6].includes(form.value.statusId);
    });

    // 获取提交按钮文本
    const getSubmitButtonText = () => {
      if (!form.value.statusId || form.value.statusId === 1) {
        return '提交审核';
      } else if ([4, 5, 6].includes(form.value.statusId)) {
        return '重新提交';
      } else {
        return '保存';
      }
    };

    // 暂存功能
    const onSaveDraft = async () => {
      try {
        savingDraft.value = true;
        
        // 暂存时只需要基本的课程和学期信息
        if (!form.value.courseId || !form.value.termId) {
          ElMessage.warning('请至少选择课程和学期');
          return;
        }
        
        // 保持当前状态或设为草稿状态
        const draftData = {
          ...form.value,
          statusId: 1 // 草稿状态
        };
        
        if (isEdit.value) {
          await updateKcjxzj(route.params.id, draftData);
          ElMessage.success('暂存成功');
        } else {
          await createKcjxzj(draftData);
          ElMessage.success('暂存成功');
        }
        
        // 返回到课程总结浏览页面
        router.push('/kcjxzj/summary-browse');
      } catch (error) {
        console.error('暂存失败:', error);
        ElMessage.error('暂存失败');
      } finally {
        savingDraft.value = false;
      }
    };

    const onSubmit = async () => {
      try {
        await formRef.value.validate();
        submitting.value = true;
        
        let submitData;
        
        if ([1, 4, 5, 6].includes(form.value.statusId)) {
          // 草稿或驳回状态提交为待审核
          submitData = {
            ...form.value,
            statusId: 2 // 待审核状态
          };
        } else {
          // 其他状态保持原状态
          submitData = form.value;
        }
        
        // 添加当前用户ID作为teacherId（后端要求必须字段）
        if (userStore.userId) {
          submitData.teacherId = Number(userStore.userId);
        }
        
        if (isEdit.value) {
          await updateKcjxzj(route.params.id, submitData);
          ElMessage.success('更新成功');
        } else {
          await createKcjxzj(submitData);
          ElMessage.success('创建成功');
        }
        
        // 返回到课程总结浏览页面
        router.push('/kcjxzj/summary-browse');
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败: ' + (error.response?.data?.message || error.message));
      } finally {
        submitting.value = false;
      }
    };

    const onCancel = () => {
      router.go(-1);
    };

    // 页面初始化
    onMounted(async () => {
      await fetchBaseData();
      
      // 如果是编辑模式，加载现有数据
      if (isEdit.value) {
        await loadExistingSummary();
      } else {
        // 新建模式，从URL参数初始化
        initFromCourseParams();
        
        // 如果有指定的教学任务ID，预填相关信息
        if (route.query.missionId) {
          await initFromSelectedMission(route.query.missionId);
        }
      }
    });

    return {
      formRef,
      loading,
      submitting,
      savingDraft,
      isEdit,
      isReadonly,
      currentMissionId,
      form,
      courses,
      terms,
      teachingMissions,
      departments,
      rules,
      canSaveDraft,
      getSubmitButtonText,
      onSaveDraft,
      onSubmit,
      onCancel,
      onMissionsChanged,
      router
    };
  }
};
</script>

<style scoped>
.kcjxzj-summary-edit {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.actions {
  margin-left: auto;
}

.form-card {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .actions {
    margin-left: 0;
  }
}
</style>
